import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';

class UIDemo extends MaterialPageRoute<Null> {
    UIDemo()
        : super(builder: (BuildContext ctx) {
        return Demo1CreateTab();
    });
}

class Demo1CreateTab extends StatefulWidget {
    @override
    State<StatefulWidget> createState() {
        return TabSate();
    }
}

final mainKey = GlobalKey<ScaffoldState>();

class TabSate extends State<Demo1CreateTab> with SingleTickerProviderStateMixin {
    //注意此处的with含义，代表这个类可以使用with后面的类的方法而没有继承关系，类似于java的implements
    
    TabController tabController;
    
    @override
    void initState() {
        super.initState();
        
        tabController = TabController(length: 4, initialIndex: 1, vsync: this); //this指代的是SingleTickerProviderStateMixin里的 Ticker
    }
    
    @override
    void dispose() {
        tabController.dispose();
        super.dispose();
    }
    
    TabBar createTabBar() {
        return TabBar(
            tabs: <Tab>[
                Tab(
                    text: "qwer",
                    icon: Icon(Icons.home),
                ),
                Tab(
                    text: "GridView",
                    icon: Icon(Icons.home),
                ),
                Tab(
                    text: "Stepper",
                    icon: Icon(Icons.cake),
                ),
                Tab(
                    text: "Form",
                    icon: Icon(Icons.input),
                ),
            ],
            controller: tabController,
        );
    }
    
    TabBarView createTabBarView(bars) {
        return TabBarView(
            children: bars,
            controller: tabController,
        );
    }
    
    @override
    Widget build(BuildContext context) {
        return Scaffold(
            key: mainKey,
            appBar: AppBar(
                title: Text("几个常用的神奇控件"),
                bottom: createTabBar(),
            ),
            body: createTabBarView(<Widget>[
                Text("data"),
                Demo2CreateGridView().createGridView(),
                StepperDemo(),
                InputBox()
            ]),
            resizeToAvoidBottomInset: false,//输入框抵住键盘
        );
    }
}

class Demo2CreateGridView {
    Card createGridCell(String name, IconData icon) {
        return Card(
            elevation: 1.0,
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                verticalDirection: VerticalDirection.down,
                children: <Widget>[
                    Center(
                        child: Icon(icon),
                    ),
                    Text(name)
                ],
            ),
        );
    }
    
    GridView createGridView() {
        return GridView.count(
            primary: true,
            padding: EdgeInsets.all(4.0),
            crossAxisCount: 3,
            childAspectRatio: 1.0,
            mainAxisSpacing: 5.0,
            crossAxisSpacing: 10.0,
            children: <Widget>[
                createGridCell("a", Icons.accessibility),
                createGridCell("b", Icons.battery_full),
                createGridCell("c", Icons.call),
                createGridCell("d", Icons.delete),
                createGridCell("e", Icons.edit),
                createGridCell("f", Icons.face),
                createGridCell("g", Icons.gamepad),
                createGridCell("h", Icons.hd),
                createGridCell("i", Icons.image),
                createGridCell("j", Icons.format_align_justify),
                createGridCell("k", Icons.keyboard),
                createGridCell("l", Icons.label),
            ],
        );
    }
    
}

class StepperDemo extends StatefulWidget {
    @override
    State<StatefulWidget> createState() {
        return StepperState();
    }
    
}

class StepperState extends State<StepperDemo> {
    
    int stepCount = 0;
    List<Step> steps = [
        Step(title: Text("1"), content: Text("step1"), isActive: true),
        Step(title: Text("2"), content: Text("step2"), isActive: true),
        Step(title: Text("3"), content: Text("step3"), isActive: true),
        Step(title: Text("4"), content: Text("step4"), isActive: true),
        Step(title: Text("5"), content: Text("step5"), isActive: true),
        Step(title: Text("6"), content: Text("step6"), isActive: true),
        Step(title: Text("7"), content: Text("step7"), isActive: true),
        Step(title: Text("8"), content: Text("step8"), isActive: true),
    ];
    
    @override
    Widget build(BuildContext context) {
        return Container(
            child: Stepper(
                steps: steps,
                currentStep: stepCount,
                type: StepperType.vertical,
                onStepTapped: (step) {
                    setState(() {
                        stepCount = step;
                    });
                },
                onStepCancel: () {
                    setState(() {
                        stepCount > 0 ? stepCount-- : stepCount = 0;
                    });
                },
                onStepContinue: () {
                    setState(() {
                        stepCount < steps.length - 1 ? stepCount++ : stepCount = 0;
                    });
                },
            ),
        );
    }
    
}

class InputBox extends StatefulWidget {
    @override
    State<StatefulWidget> createState() {
        return InputBoxState();
    }
    
}

class InputBoxState extends State<InputBox> {
    Future<SharedPreferences> _sp = SharedPreferences.getInstance();
    bool loggedIn = false;
    String _email, _username, _password;
    
    final formKey = GlobalKey<FormState>();
    
    @override
    void initState() {
        super.initState();
        getLoggedIn();
    }
    
    @override
    Widget build(BuildContext context) {
        //getLoggedIn();
        return SingleChildScrollView( //键盘弹出时需滑动否则报错 bottom overflowed by xxxx PIXELS
            child: Padding(
                padding: EdgeInsets.all(10.0),
                child: (!loggedIn) ? Form(
                    key: formKey,
                    child: Column(
                        children: <Widget>[
                            
                            TextFormField(
                                autocorrect: false,
                                decoration: InputDecoration(labelText: "Email:"),
                                validator: (str) {
                                    if (!str.contains("@")) {
                                        return "not a email";
                                    } else {
                                        return null;
                                    }
                                },
                                onSaved: (str) {
                                    _email = str;
                                },),
                            TextFormField(
                                autocorrect: false,
                                decoration: InputDecoration(labelText: "Username:"),
                                validator: (str) {
                                    if (str.length < 4) {
                                        return "not a username";
                                    } else {
                                        return null;
                                    }
                                },
                                onSaved: (str) {
                                    _username = str;
                                },),
                            TextFormField(
                                autocorrect: false,
                                decoration: InputDecoration(labelText: "Password:"),
                                validator: (str) {},
                                onSaved: (str) {
                                    _password = str;
                                },
                                obscureText: true,
                            ),
                            RaisedButton(
                                child: Text("log in"),
                                onPressed: () {
                                    var form = formKey.currentState;
                                    if (form.validate()) {
                                        form.save();
                                        setState(() {
                                            loggedIn = true;
                                        });
                                        
                                        saveLoggedIn();
                                        
                                        var snackBar = SnackBar(
                                            content: Text("UserName:$_username,Email:$_email,Password:$_password"),
                                            duration: Duration(seconds: 10),
                                        );
                                        mainKey.currentState.showSnackBar(snackBar);
                                    }
                                },
                            )
                        
                        ],
                    )
                ) : Center(
                    child: Column(
                        children: <Widget>[
                            Text("UserName:$_username,Email:$_email,Password:$_password"),
                            RaisedButton(
                                child: Text("log out"),
                                onPressed: () {
                                    saveLoggedOut();
                                    setState(() {
                                        loggedIn = false;
                                    });
                                },
                            )
                        ],
                    ),
                )
            
            ),
        );
    }
    
    Future<Null> saveLoggedOut() async {
        final SharedPreferences sp = await _sp;
        sp.setBool("LOGGEDIN", false);
        sp.setString("USERNAME", "");
        sp.setString("EMAIL", "");
        sp.setString("PASSWORD", "");
    }
    
    saveLoggedIn() {
        _sp.then((SharedPreferences sp) {
            sp.setBool("LOGGEDIN", loggedIn);
            sp.setString("USERNAME", _username);
            sp.setString("EMAIL", _email);
            sp.setString("PASSWORD", _password);
        });
    }
    
    Future<Null> getLoggedIn() async {
        final SharedPreferences sp = await _sp;
        setState(() {
            loggedIn = sp.getBool("LOGGEDIN") ?? false;
            _username = sp.getString("USERNAME") ?? "";
            _email = sp.getString("EMAIL") ?? "";
            _password = sp.getString("PASSWORD") ?? "";
        });
    }
}